package oop.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import oop.controller.action.DefaultAction;

import org.apache.commons.lang.StringUtils;

/**
 * Servlet implementation class Test
 */
public class ControllerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public String getActionURL(String action) {
		return "?action=" + action;
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		process(request, response);
	}

	@SuppressWarnings("unchecked")
	protected void process(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		// set encoding
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");

		// set environmental variables
		String name = "index.jsp";
		request.setAttribute("homeDir", "http://localhost:8080/tracnghiem");
		request.setAttribute("scriptPath", request.getAttribute("homeDir")
				+ "/" + name);
		if (request.getSession().getAttribute("template") == null) {
			request.getSession().setAttribute("template", "default");
		}
		request
				.setAttribute("templateDir", request.getAttribute("homeDir")
						+ "/templates/"
						+ request.getSession().getAttribute("template"));

		// perform action
		try {
			// get action
			String actionStr = StringUtils.defaultIfEmpty(request
					.getParameter("action"), "homepage");
			String className = StringUtils.defaultIfEmpty(
					getInitParameter(actionStr),
					"oop.controller.action.NoSuchAction");
			DefaultAction action = ((Class<? extends DefaultAction>) Class
					.forName(className)).newInstance();
			// perform
			action.setController(this);
			action.setRequest(request);
			action.setResponse(response);
			action.perform();
			// forward next action or jsp
			if (!action.isPreventForward()) {
				if (action.getNextAction() != null) {
					String uri = name + "?action=" + action.getNextAction();
					request.getRequestDispatcher(uri)
							.forward(request, response);
				} else {
					String uri = "templates/"
							+ request.getSession().getAttribute("template")
							+ "/index.jsp?action=" + actionStr;
					request.getRequestDispatcher(uri)
							.forward(request, response);
				}
			}
		} catch (ClassNotFoundException e) {
			// XXX
			throw new RuntimeException(e);
		} catch (Exception e) {
			// XXX
			throw new RuntimeException(e);
		}
	}

}
